<template>
  <div class="container">
    <!-- 图标组件 -->
    <IconTubiao @satellite="handleSatellite" v-show="!fullscreenShow"></IconTubiao>
    <!-- 下载APP组件 -->
    <DownLoadApp v-show="!fullscreenShow"></DownLoadApp>
    <!-- 登录入口组件 -->
    <LoginEnter v-show="!fullscreenShow" @selectmap="handleSelectMap"></LoginEnter>
    <!-- 搜索组件 -->
    <SearchLoad
      v-show="!fullscreenShow"
      @inputSearch="handleInputSearch"
      @handleType="handleType"
      @keywordSearch="handleKeywordSearch"
    ></SearchLoad>
    <!-- 本地温度组件 -->
    <LocalTemplete
      :localCity="localCity"
      v-show="!fullscreenShow"
      :localLemplete="localLemplete"
    ></LocalTemplete>
    <!-- 导航组件 -->
    <NavigationRoad @handleGoingTo="handleGoingTo"></NavigationRoad>
    <!-- 退出全屏按钮 -->
    <div class="closefullscreen" :class="{ show: fullscreenShow }">
      <button @click="fullscreenShow = !fullscreenShow">退出全屏</button>
    </div>
    <!-- 搜索到的位置列表 -->
    <div class="search-item" :class="{ show: showSearchItem }">
      <div class="search-name">
        <div class="name">{{ itemArr[0] }}</div>
        <div class="address">{{ itemArr[1] }}</div>
        <div class="go-phone">
          <i class="iconfont icon-phone"></i>
          <span>去手机查看详情</span>
        </div>
      </div>
      <div class="gaode-phone">
        <div class="left">
          <div class="one">高德地图手机版</div>
          <div class="two">高德地图 哪儿都熟</div>
          <div class="three">去官网下载</div>
        </div>
        <div class="right">
          <img src="/public/img/二维码.png" />
        </div>
      </div>
    </div>
    <!-- 通过关键字搜索的位置列表 -->
    <div id="panel" :class="{ showpanel: showPanel }"></div>
  </div>
  <!-- 导航路线列表 -->
  <div id="panel-driving" :class="{ showpanel: showPanelDriving }"></div>
  <!-- 登录页面 -->
  <div class="login-yemian" :class="{ showLogin: showLogins }">
    <div class="left">
      <img src="/public/img/loginimg.jpg" alt="" />
    </div>
    <div class="right">
      <h2>账号密码登录</h2>
      <div class="cancel" @click="changeShowLogins()">×</div>
      <input type="text" placeholder="请输入账号" v-model="account"><br>
      <input type="password" placeholder="请输入密码" v-model="password"><br>
      <button class="login-btn" @click="handleLogin">登录</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import IconTubiao from './components/IconTubiao.vue'
import DownLoadApp from './components/DownLoadApp.vue'
import LoginEnter from './components/LoginEnter.vue'
import SearchLoad from './components/SearchLoad.vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import LocalTemplete from './components/LocalTemplete.vue'
import NavigationRoad from './components/NavigationRoad.vue'
import useControls from './hooks/useControls.js'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useCounterStore } from './stores/counter.js'
import { storeToRefs } from 'pinia'
const { changeShowPanelDriving,changeShowPanelDrivingTrue,changeShowPanelDrivingFalse, changeShowLogins,changeLogined } = useCounterStore()
const { localCity, cityAdcode,localLemplete,showPanelDriving, showLogins,logined } = storeToRefs(useCounterStore())

const satelliteShow = ref(false) // 是否显示卫星和路网地图
const trafficShow = ref(false) // 是否显示路况
const mouseToolShow = ref(false) // 是否显示鼠标测距工具

const fullscreenShow = ref(false) // 是否全屏

const showSearchItem = ref(false) // 是否显示某一个的搜索列表
let itemArr = ref([]) // 某一个搜索列表的信息
const showPanel = ref(false) // 搜索种类
const account = ref('') // 登录账号
const password = ref('') // 登录密码
let AMap
let map
let mapCenter = ref([]) // 定位插件查询的地图中心点
let satellite // 卫星地图
let roadNet //路网地图
let traffic //路况地图
let mouseTool //鼠标测距工具

let markers = [] // 空气质量标记点数组
let labelsLayer = null // 空气质量图层

let infoWindow // 用于创建点击后的信息窗体
// 空气质量函数
const airQuality = async () => {
  // 先判断之前是否已经创建,有就清除,没有就创建
  if (markers.length === 0) {
    labelsLayer = new AMap.LabelsLayer({
      zooms: [3, 20],
      zIndex: 1000,
      collision: true,
      allowCollision: true,
    })
    map.add(labelsLayer)
    //设置一个图标对象
    let icon = {
      type: 'image',
      image: '/img/point.png',
      size: [15, 15], //图片尺寸
      anchor: 'center', //图片相对 position 的锚点
    }
    // 使用fetch请求城市空气质量数据
    const res = await fetch(
      `/calendar/environment/air/cityair?key=0f309ab3c0b3ebcd744f9cab34bb8bd4&city=武汉`,
    )
    const datas = await res.json()
    const lastMoniData = datas.result[0].lastMoniData
    const length = Object.keys(lastMoniData).length

    // 遍历数据,创建所有的LabelMarker
    for (let i = 1; i <= length; i++) {
      let lng = lastMoniData[i].lon
      let lat = lastMoniData[i].lat
      //创建 LabelMarker
      let pointer = {
        position: [lng, lat],
        icon: icon,
      }
      let labelMarker = new AMap.LabelMarker(pointer)
      markers.push(labelMarker)
      // 鼠标点击,根据请求数据信息创建信息窗口
      labelMarker.on('click', function (e) {
        let position = e.data.data && e.data.data.position
        if (position) {
          let content = `<div class='marker-content'>
            <div class='title'>
              <div>${lastMoniData[i].city}空气质量</div>
              <div>AQI</div>
              <div>PM2.5Day</div>
            </div>
            <div class='content'>
              <div class='content-item'>${lastMoniData[i].quality}</div>
              <div>${lastMoniData[i].AQI}</div>
              <div>${lastMoniData[i]['PM2.5Day']}</div>
              </div>
          </div>`
          infoWindow = new AMap.InfoWindow({
            content: content,
            anchor: 'top-center',
          })
          infoWindow.open(map, position)
        }
      })
    }
    //全部marker添加到图层上
    labelsLayer.add(markers)
  } else {
    markers = []
    map.remove(labelsLayer)
  }
}

// icontubiao组件点击事件,加载卫星地图,空气质量,路况,测距,全屏
const handleSatellite = (index) => {
  if (index === 0) {
    satelliteShow.value = !satelliteShow.value
    if (satelliteShow.value) {
      satellite = new AMap.TileLayer.Satellite()
      roadNet = new AMap.TileLayer.RoadNet()
      map.addLayer(roadNet)
      map.addLayer(satellite)
    } else {
      map.removeLayer(satellite)
      map.removeLayer(roadNet)
    }
  }
  if (index === 1) {
    map.setZoom(10)
    airQuality()
  }
  if (index === 2) {
    trafficShow.value = !trafficShow.value
    if (trafficShow.value) {
      traffic = new AMap.TileLayer.Traffic({
        autoRefresh: true,
        interval: 180,
      })
      map.addLayer(traffic)
    } else {
      map.removeLayer(traffic)
    }
  }
  if (index === 3) {
    mouseToolShow.value = !mouseToolShow.value
    if (mouseToolShow.value) {
      mouseTool = new AMap.MouseTool(map)
      // 测量距离
      mouseTool.rule({
        startMarkerOptions: {
          //设置量测起始点标记属性对象 可缺省
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31), //图标大小
            imageSize: new AMap.Size(19, 31),
            image: '//webapi.amap.com/theme/v1.3/markers/b/start.png',
          }),
          offset: new AMap.Pixel(-9, -31),
        },
        endMarkerOptions: {
          //设置量测结束点标记属性对象 可缺省
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31), //图标大小
            imageSize: new AMap.Size(19, 31),
            image: '//webapi.amap.com/theme/v1.3/markers/b/end.png',
          }),
          offset: new AMap.Pixel(-9, -31),
        },
        midMarkerOptions: {
          //设置拖拽路线插件途经点点标记属性对象 可缺省
          icon: new AMap.Icon({
            size: new AMap.Size(19, 31), //图标大小
            imageSize: new AMap.Size(19, 31),
            image: '//webapi.amap.com/theme/v1.3/markers/b/mid.png',
          }),
          offset: new AMap.Pixel(-9, -31),
        },
        lineOptions: {
          //可缺省
          strokeStyle: 'solid',
          strokeColor: '#FF33FF',
          strokeOpacity: 1,
          strokeWeight: 2,
        },
      })
    } else {
      mouseTool.close()
    }
  }
  if (index === 5) {
    fullscreenShow.value = !fullscreenShow.value
  }
}

// localtemplete组件点击事件等到本地城市adcode请求成功时,请求天气
watch(
  () => cityAdcode.value,
  async () => {
    const res = await axios.get(
      `https://restapi.amap.com/v3/weather/weatherInfo?city=${cityAdcode.value}&key=b246d3d6954ef868e6b9af454d7ad5c2&extensions=all`,
    )
    const { nighttemp, daytemp, dayweather } = res.data.forecasts[0].casts[0]
    localLemplete.value.push(daytemp)
    localLemplete.value.push(nighttemp)
    localLemplete.value.push(dayweather)
  },
)

// searchload组件输入事件:创建输入提示插件
const handleInputSearch = (keyword) => {
  // 如果没值,那么收起某一个的搜索信息,收起关键字查询列表
  if (!keyword.trim()) {
    showSearchItem.value = false
    showPanel.value = false
  }
  // 搜索提示插件
  const autoComplete = new AMap.AutoComplete({
    city: `${cityAdcode.value}`,
    input: 'searchinput',
  })
  // POI搜索插件
  const placeSearch = new AMap.PlaceSearch({
    city: `${cityAdcode.value}`,
    map: map,
  })
  //  搜索点击事件(第一次请求失败?)
  autoComplete.on('select', function (e) {
    placeSearch.search(e.poi.name)
    if (e.poi.district && e.poi.address && e.poi.location) {
      showSearchItem.value = true
      itemArr.value = [e.poi.name, e.poi.address, e.poi.location]
    }
  })
}
// searchload组件
// 种类搜索函数
function typeSearch(type) {
  let placeSearch = new AMap.PlaceSearch({
    pageSize: 6, // 单页显示结果条数
    pageIndex: 1, // 页码
    city: `${localCity.value}`, // 兴趣点城市
    citylimit: true, //是否强制限制在设置的城市内搜索
    map: map, // 展现结果的地图实例
    panel: 'panel', // 结果列表将在此容器中进行展示。
  })
  let cpoint = mapCenter.value //中心点坐标
  placeSearch.searchNearBy(`${type}`, cpoint, 2000)
}
// 种类搜索事件
const handleType = (type) => {
  if (type == '0') {
    typeSearch('美食')
  } else if (type == '1') {
    typeSearch('酒店')
  } else if (type == '2') {
    typeSearch('景点')
  } else if (type == '3') {
    typeSearch('小区')
  }
  showPanel.value = true//列表容器展示
}
// 关键字搜索事件
const handleKeywordSearch = (keyword) => {
  typeSearch(`${keyword}`)
  showPanel.value = true
}

// NavigationRoad组件点击事件,加载导航路线
let driving = null
let transfer = null
let walking = null
// 清除搜索函数
const clearSearch = ()=>{
// 绘制前先清除之前的搜索结果(包括展示列表和路线)
    if(walking){
      walking.clear()
    }
    if(driving){
      driving.clear()
    }
    if(transfer){
      transfer.clear()
    }
}
const handleGoingTo = (keyword) => {
  // 开车导航
  if (keyword[2] == '0') {
    ElMessage({
      message: '正在查询',
      type: 'info',
      duration: 500,
    })
    clearSearch()//清除之前的绘制
    driving = new AMap.Driving({
      map: map,
      panel: 'panel-driving',
    })

    const points = [
      { keyword: `${keyword[0]}`, city: `${cityAdcode.value}` },
      { keyword: `${keyword[1]}`, city: `${cityAdcode.value}` },
    ]
    driving.search(points)
    changeShowPanelDrivingTrue()
  }
  // 公交导航
  if (keyword[2] == '1') {
    ElMessage({
      message: '正在查询',
      type: 'info',
      duration: 500,
    })
    clearSearch()//清除之前的绘制
    const transOptions = {
      map: map,
      city: `${cityAdcode.value}`,
      panel: 'panel-driving',
    }
    transfer = new AMap.Transfer(transOptions)
    transfer.search([{ keyword: keyword[0] }, { keyword: keyword[1] }])
    changeShowPanelDrivingTrue()
    }
    
    // 步行导航
  if (keyword[2] == '2') {
    ElMessage({
      message: '正在查询',
      type: 'info',
      duration: 500,
    })
    clearSearch()//清除之前的绘制
    walking = new AMap.Walking({
      map: map,
      panel: 'panel-driving',
    })
    walking.search([{ keyword: keyword[0] }, { keyword: keyword[1] }])
    changeShowPanelDrivingTrue()
  }
  }
  


// loginenter组件切换地图
const handleSelectMap = (index) => {
  switch (index) {
    case 0:
      map.setMapStyle('amap://styles/normal')
      break
    case 1:
      map.setMapStyle('amap://styles/blue')
      break
    case 2:
      map.setMapStyle('amap://styles/dark')
      break
  }
}

  // 登录事件
const handleLogin = async() => {
  if( account.value && password.value){
    const res = await axios.get('http://localhost:3000/data')
    const datas = res.data
    console.log(datas)
    console.log(account.value,password.value)
    const user = datas.find(item => item.name == account.value && item.password == password.value)
    console.log(user)
    if(user){
      changeLogined()//改为登录成功状态
      changeShowLogins()//去掉登录界面
      ElMessage.success('登录成功')
      account.value = ''
      password.value = ''
    }else{
      ElMessage.error('账号或密码错误')
    }
  }else{
   ElMessage.error('账号密码不能为空')
  }
}
onMounted(async () => {
  window._AMapSecurityConfig = {
    securityJsCode: 'b979cfd7c797959b0254ac160744a44d',
  }
  AMap = await AMapLoader.load({
    key: 'd1cb1427b4915c564ab9403bd14af829',
    version: '2.0',
    plugins: [
      'AMap.Scale',
      'AMap.ControlBar',
      'AMap.ToolBar',
      'AMap.Geolocation',
      'AMap.CitySearch',
      'AMap.MouseTool',
      'AMap.AutoComplete',
      'AMap.PlaceSearch',
      'AMap.Geocoder',
      'AMap.Driving',
      'AMap.Transfer',
      'AMap.Walking',
    ],
  })
  map = new AMap.Map('container', {
    viewMode: '3D',
    center: [114.3, 30.5],
    zoom: 10,
    // mapStyle: 'amap://styles/macaron',
  })
  // 加载控件
  useControls(map, AMap)
  // 加载定位组件 通过指定ip查询
  const citySearch = new AMap.CitySearch()
  citySearch.getCityByIp('59.68.0.0', (status, result) => {
    if (status === 'complete' && result.info === 'OK') {
      // 将边界的两个字符串经纬度,转为中心点经纬度
      let lngLat = result.rectangle.split(';').map((point) => {
        const [lng, lat] = point.split(',').map(Number)
        return { lng, lat }
      })
      let lng = lngLat.reduce((acc, cur) => acc + cur.lng, 0) / lngLat.length
      let lat = lngLat.reduce((acc, cur) => acc + cur.lat, 0) / lngLat.length
      // 获取对应的城市,adcode,经纬度
      localCity.value = result.city
      cityAdcode.value = result.adcode
      mapCenter.value = [lng, lat]
      map.setCenter([lng, lat])
    }
  })
})
</script>

<style lang="scss">
@import '//at.alicdn.com/t/c/font_4946657_x5pf4ygpc2.css';
.amap-controlbar {
  //控件样式
  transform: scale(0.7);
}
.container {
  position: relative;
  z-index: 99;
  .closefullscreen {
    position: absolute;
    top: -50px;
    right: 50px;
    transition: all 0.1s ease;
    opacity: 0;
    button {
      width: 80px;
      height: 40px;
      background: #fff;
      border: none;
      outline: none;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
      color: #666;
      &:hover {
        color: #999;
      }
    }
    &.show {
      top: 70px;
      opacity: 1;
    }
  }
  // 点击搜索某一个的信息列表
  .search-item {
    box-shadow: 0 2px 3px rgba(0, 0, 0, 0.3);
    background: #fff;
    position: absolute;
    top: 55px;
    left: 10px;
    padding: 20px;
    height: 0px;
    opacity: 0;
    pointer-events: none;
    transition: all 0.3s ease-in-out;
    &.show {
      opacity: 1;
      height: 220px;
      pointer-events: auto;
    }
    .search-name {
      color: #666;
      font-size: 14px;
      .address {
        font-size: 13px;
        color: #999;
        margin: 5px 0;
      }
      .go-phone {
        color: rgb(26, 134, 2455);
        font-size: 13px;
      }
    }
    .gaode-phone {
      display: flex;
      gap: 100px;
      justify-content: space-between;
      margin-top: 20px;
      .left {
        font-size: 12px;
        color: #666;
        .one {
          font-size: 16px;
          font-weight: 700;
          color: rgb(26, 134, 2455);
        }
        .three {
          text-align: center;
          line-height: 35px;
          color: #fff;
          width: 120px;
          height: 35px;
          background: rgb(26, 134, 2455);
          border-radius: 20px;
          margin-top: 10px;
        }
      }
      .right {
        img {
          width: 88px;
          height: 88px;
        }
      }
    }
  }
}

// 信息弹窗
.marker-content {
  padding: 15px 10px;
  font-size: 14px;
  color: #666;
  display: flex;
  gap: 20px;
  .content-item {
    color: rgba(68, 234, 71, 0.639);
  }
}

// 搜索插件的搜索框
.amap-sug-result {
  width: 345px;
  transform: translateX(-55px) translateY(3px);
  box-shadow: 0 0px 1px rgba(0, 0, 0, 0.3);
  .auto-item {
    color: #333;
    margin: 5px 0;
    &:hover {
      background: #eee;
    }
  }
}

// 通过关键字搜索的容器
#panel {
  position: fixed;
  background-color: white;
  overflow-y: auto;
  top: 300px;
  left: 10px;
  width: 350px;
  border-bottom: solid 1px silver;
  transition: all 0.7s ease-in-out;
  max-height: 0px;
  opacity: 0;
  pointer-events: none;
  &.showpanel {
    max-height: 550px;
    opacity: 1;
    pointer-events: auto;
  }
}
// 通过关键字搜索的容器
#panel-driving {
  position: fixed;
  background-color: white;
  overflow-y: auto;
  top: 100px;
  right: 10px;
  width: 300px;
  border-bottom: solid 1px silver;
  transition: all 0.7s ease-in-out;
  max-height: 0px;
  opacity: 0;
  pointer-events: none;
  z-index: 300;
  &.showpanel {
    max-height: 550px;
    opacity: 1;
    pointer-events: auto;
  }
}

  // 登录页面
.login-yemian {
  position: absolute;
  top: 50%;
  left: 50%;
  display: flex;
  transform: translate(-50%, -50%);
  background: #fff;
  z-index: 100;
  display: none;
  pointer-events: auto;
  &.showLogin {
    display: flex;
    pointer-events: auto;
  }
  .left {
    width: 350px;
    height: 500px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .right {
    position: relative;
    padding: 50px;
    h2 {
      font-weight: 400;
      margin-bottom: 20px;
    }
    .cancel{
      position: absolute;
      top: 20px;
      right: 20px;
      font-size: 16px;
      color: #666;
      cursor: pointer;
    }
    input{
      margin: 15px 0px;
      padding: 0 5px;
      border: none;
      outline: none;
      border: 1px solid #ccc;
      height: 40px;
      width: 250px;
      border-radius: 5px;
    }
    .login-btn{
      cursor: pointer;
      width: 100px;
      height: 40px;
      background: rgb(82, 172, 246);
      border: none;
      outline: none;
      color: #fff;
      border-radius: 5px;
      &:hover{
        background: rgb(41, 143, 227);
      }
      &:active{
        background: rgb(7, 113, 219);
      }
    }
  }
}

</style>
